#include <iostream>
#include "../Api Headers/DataTree.hpp"
#include "RequestParser.hpp"

RequestParser::RequestParser()
{

}

RequestParser::~RequestParser()
{

}

void		RequestParser::ParseRequest(const std::string &Request, zia::api::DataTree &Tree, std::string &Body)
{
  GetHeader(Request, Body);
  ParseFirstLine(Tree);
  ParseHeader(GetNextLine(), Tree);
  Tree.print(std::cout);
}

void		RequestParser::GetHeader(const std::string &Request, std::string &Body)
{
  this->_request = Request.substr(0, Request.find("\r\n\r") + 2);
  Body = Request.substr(Request.find("\r\n\r") + 3, Request.size() - (Request.find("\r\n\r") + 3));
  std::cout << this->_request << "\n------------- Parsing -------------\n";
}

void		RequestParser::ParseFirstLine(zia::api::DataTree &Tree)
{
  std::string	tmp = this->_request.substr(0, this->_request.find("\r\n"));

  this->_request.erase(0, this->_request.find("\r\n") + 2);
//   tmp.erase(0, tmp.find(':') + 2);
  Tree["Method"] = tmp.substr(0, tmp.find(' '));
  Tree["URL"] = tmp.substr(tmp.find(' ') + 1, tmp.rfind(' ') - (tmp.find(' ') + 1));
  Tree["Version"] = tmp.substr(tmp.rfind(' ') + 1, tmp.find("\r\n"));
}

std::string	RequestParser::GetNextLine()
{
  std::string	to_parse;
  to_parse = this->_request.substr(0, this->_request.find("\r\n"));
  this->_request.erase(0, this->_request.find("\r\n") + 2);
  return (to_parse);
}

void		RequestParser::ParseHeader(std::string to_parse, zia::api::DataTree &Tree)
{
  if (to_parse.empty() || to_parse == "\r\n")
    return ;
  else
    {
      Tree[to_parse.substr(0, to_parse.find(": "))] = to_parse.substr(to_parse.find(": ") + 2, to_parse.find("\r\n") - to_parse.find(": "));
      ParseHeader(GetNextLine(), Tree);
    }
  return ;
}
